﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfTest;

namespace UbiGamesBackupTool
{
    /// <summary>
    /// ChooseListenerGameWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ChooseListenerGameWindow : Window
    {
        ImageBrush GameBtnDefaultImageBrush = null;
        SolidColorBrush GamePanelColorBrush = null;
        SolidColorBrush GamePanelSelectedColorBrush = null;
        List<Game> SelectGameList = new List<Game>();
        public ChooseListenerGameWindow()
        {
            InitializeComponent();
            GameBtnDefaultImageBrush = (ImageBrush)FindResource("GameBtnDefaultImageBrush");            //寻找资源
            GamePanelColorBrush = (SolidColorBrush)FindResource("GamePanelColorBrush");                 //
            GamePanelSelectedColorBrush = (SolidColorBrush)FindResource("GamePanelSelectedColorBrush"); //
        }

        /// <summary>
        /// 初始化游戏列表
        /// </summary>
        public void InitGameListPanel()
        {
            GameListView.Children.Clear();
            List<Game> Ugamelist = MainWindow.GetSupportGame();
            List<Game> HavedGameList = GetHavedGameList();
            foreach (Game g in Ugamelist)
            {
                if (g.Title != "")
                {
                    //----------------------开始添加一个游戏在列表中---------------------
                    WrapPanel panel = new WrapPanel
                    {
                        Width = 330,
                        HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
                        Margin = new Thickness(4, 4, 4, 4),
                    };
                    if ((from game in HavedGameList where game.id == g.id select game).Count() == 1)
                    {
                        SelectGameList.Add(g);
                        panel.Background = GamePanelSelectedColorBrush;
                    }
                    else
                    {
                        panel.Background = GamePanelColorBrush;
                    }
                    System.Windows.Controls.Button pictureBox = new System.Windows.Controls.Button
                    {
                        Width = 330,
                        Height = 181
                    };
                    System.Windows.Controls.Label label = new System.Windows.Controls.Label { Width = 330 };
                    panel.Children.Add(pictureBox);
                    panel.Children.Add(label);
                    GameListView.Children.Add(panel);

                    ImageBrush imageBrush = new ImageBrush();
                    if (File.Exists(MainWindow.GAMELOGOCACHE + "\\" + g.img))
                    {
                        imageBrush.ImageSource = new BitmapImage(new Uri(MainWindow.GAMELOGOCACHE + "\\" + g.img));
                        pictureBox.Background = imageBrush;
                    }
                    else
                    {
                        pictureBox.Background = GameBtnDefaultImageBrush;
                    }

                    pictureBox.Click += new RoutedEventHandler(this.GamePanelClicked);
                    pictureBox.Tag = g;

                    label.Content = g.name + "-" + g.Version;
                    label.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center;

                }
            }
            GC.Collect();
        }
        /// <summary>
        /// 游戏列表中 pictureBox的点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GamePanelClicked(object sender, EventArgs e)
        {
            System.Windows.Controls.Button pictureBox = (System.Windows.Controls.Button)sender;
            WrapPanel wrapPanel = (WrapPanel)pictureBox.Parent;
            Game g = pictureBox.Tag as Game;
            if (SelectGameList.Contains(g))
            {
                SelectGameList.Remove(g);
                wrapPanel.Background = GamePanelColorBrush;
            }
            else
            {
                SelectGameList.Add(g);
                wrapPanel.Background = GamePanelSelectedColorBrush;
            }
        }
        /// <summary>
        /// 从bitmap转换成ImageSource
        /// </summary>
        /// <param name="icon"></param>
        /// <returns></returns>
        public static ImageSource ChangeBitmapToImageSource(Bitmap bitmap)
        {
            //Bitmap bitmap = icon.ToBitmap();
            IntPtr hBitmap = bitmap.GetHbitmap();
            ImageSource wpfBitmap = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                hBitmap,
                IntPtr.Zero,
                Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());
            //if (!DeleteObject(hBitmap))
            //{

            //}
            return wpfBitmap;
        }

        private void OkBtn_Click(object sender, RoutedEventArgs e)
        {
            //code
            using (Stream stream = new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + System.IO.Path.DirectorySeparatorChar + "ListenerGameList.json",FileMode.Create))
            {
                using (StreamWriter writer = new StreamWriter(stream)) {
                    writer.WriteLine(JsonConvert.SerializeObject(SelectGameList));
                    writer.Flush();
                    writer.Close();
                    stream.Close();
                }
            }
            SelectGameList.Clear();
            GameListView.Children.Clear();
            this.Close();
        }

        private void CancelBtn_Click(object sender, RoutedEventArgs e)
        {
            SelectGameList.Clear();
            GameListView.Children.Clear();
            this.Close();
        }

        public List<Game> GetHavedGameList() {
            List<Game> HavedGamelist;
            string path = System.AppDomain.CurrentDomain.BaseDirectory + System.IO.Path.DirectorySeparatorChar + "ListenerGameList.json";
            using (Stream stream = new FileStream(path, FileMode.OpenOrCreate))
            {
                using (StreamReader reader = new StreamReader(stream))
                {
                    HavedGamelist = JsonConvert.DeserializeObject<List<Game>>(reader.ReadToEnd());
                    //如果待监听列表为空，不进行监听
                    if (HavedGamelist != null)
                    {
                        return HavedGamelist;
                    }
                }
            }
            return new List<Game>();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            InitGameListPanel();
        }
    }
}
